package com.kun.cmd.service.lmpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.cmd.mapper.DictMapper;
import com.kun.cmd.service.DictService;
import com.kun.commonutil.exception.HospitalException;
import com.kun.model.entity.cmn.Dict;
import com.kun.model.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zhoukun
 * @Date 2021/4/6 21:40
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService  {
    /**
     * 查询数据字典所有数据
     * @param id
     * @return
     */
    @Cacheable(value = "dict",key = "'commodity:'+#id")
    @Override
    public List<Dict> findChildDataById(Long id) {
        List<Dict> list = this.list(new QueryWrapper<Dict>().eq("parent_id", id));
        //遍历查询是否包含子节点
        for (Dict dict : list) {
            boolean children = isChildren(dict.getId());
            dict.setHasChildren(children);
        }
        return list;
    }


    @Override
    public void exportDict(HttpServletResponse response) throws IOException {
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        List<Dict> list = this.list();

        List<DictEeVo> collect = list.stream().map(i -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtil.copyProperties(i, dictEeVo);
            return dictEeVo;
        }).collect(Collectors.toList());
        writer.write(collect, true);
        //out为OutputStream，需要写出到的目标流
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    /**
     * 导入
     *  allEntries = true: 方法调用后清空所有缓存
     * @throws IOException
     */
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importDict(MultipartFile file) {
        if (file.isEmpty()) {
            System.out.println( "文件为空！");
           throw new HospitalException("文件不能为空",2000);
        }
        // 1.获取上传文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (Exception e) {
            //return ResponseData.fail(ResponseCodeEnum.ERROR_PARAM_INVALID);
            e.printStackTrace();
        }
//        // 2.应用HUtool ExcelUtil获取ExcelReader指定输入流和sheet
//        ExcelReader excelReader = ExcelUtil.getReader(inputStream, "导入材料清单");
//        // 可以加上表头验证
//        // 3.读取第二行到最后一行数据
//        List<List<Object>> read = excelReader.read(2, excelReader.getRowCount());
//        for (List<Object> objects : read) {
//            // objects.get(0),读取某行第一列数据
//            // objects.get(1),读取某行第二列数据
//            System.out.println(objects.get(0));
//        }

        //调用用 hutool 方法读取数据 默认调用第一个sheet
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
        List<Dict> excels = excelReader.readAll(Dict.class);
        log.info(String.valueOf(excels));
        this.saveBatch(excels);
    }

    @Override
    public String getDictName(String value) {

            Dict dict= this.baseMapper
                    .selectOne(new QueryWrapper<Dict>()
                            .eq("value", value));
            return  dict.getName();

    }

    /**
     * 根据dictCode获取下级节点
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));

        return this.baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", dict.getId()));
    }

    /**
     * 判断id是否有子节点
     */
    public  boolean isChildren(Long id){
        int parentId = this.count(new QueryWrapper<Dict>().eq("parent_id", id));
        return parentId>0;
    }
}
